<template>
  <div class="container">
    <div class="table-data">
      <el-card class="box-card">
        <!-- 提示区域 -->
        <el-alert
          title="修改商品信息"
          type="info"
          center
          show-icon
          :closable="false"
        ></el-alert>
        <!-- 步骤条区域 -->
        <el-steps
          :active="activeIndex - 0"
          finish-status="success"
          align-center
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品规格"></el-step>
          <el-step title="商品详情"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
          label-position="top"
        >
          <el-tabs
            v-model="activeIndex"
            :tab-position="'left'"
            :before-leave="beforeTabLeave"
          >
            <el-tab-pane label="基本信息" name="0" class="left-pane">
              <el-form-item label="商品名称" prop="good_name">
                <el-input v-model="editForm.good_name"></el-input>
              </el-form-item>
              <el-form-item label="封面价格" prop="price">
                <el-input v-model="editForm.price" type="number"></el-input>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品规格" name="1">
              <!-- ==================  sku规范添加  ========================== -->
              <el-form-item
                :label="index"
                v-for="(item, index) in editForm.info[0].colour"
                :key="index"
              >
                <el-input v-model="editForm.info[0].colour[index]"></el-input>
              </el-form-item>
              <el-form-item label="库存">
                <el-input
                  v-model="editForm.info[0].edition[0].inventory"
                ></el-input>
              </el-form-item>
              <el-form-item label="是否热卖">
                <el-switch
                  style="display: block"
                  v-model="value2"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="是"
                  inactive-text="否"
                  @change="switchChange"
                ></el-switch>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品详情" name="2">
              <!-- 子组件editor -->
              <editors
                :pid="6"
                :info="editForm.info[0].info"
                v-if="activeIndex == 2"
              ></editors>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
              <p class="banner-title">上传商品封面</p>

              <div class="flex-row">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="封面商品图片"
                  placement="right-start"
                >
                  <el-button
                    type="danger"
                    size="small"
                    plain
                    style="margin-bottom: 10px"
                    @click="setimg"
                    >切换修改</el-button
                  >
                </el-tooltip>
                <el-upload
                  class="upload-demo"
                  name="img"
                  action
                  :on-preview="handlePreview"
                  :http-request="uploadFile"
                  :on-remove="handleRemove"
                  :auto-upload="true"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">更换图片</el-button>
                </el-upload>
              </div>

              <el-form-item label prop="img" class="coverImg">
                <el-input v-model="editForm.img" v-if="fmImgCode"></el-input>
                <img :src="editForm.img" v-if="!fmImgCode" />
              </el-form-item>

            
              <p class="banner-title">上传轮播图</p>
              <div class="flex-row">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="商品购物详情轮播图"
                  placement="right-start"
                  transition="el-fade-in-linear"
                >
                  <el-button
                    type="danger"
                    size="small"
                    plain
                    style="margin: 0 0 10px 0"
                    @click="setLoop"
                    >切换修改</el-button
                  >
                </el-tooltip>
                <el-upload
                  class="upload-demo"
                  name="img"
                  action
                  :on-preview="handlePreview"
                  :http-request="uploadFile2"
                  :on-remove="handleRemove"
                  :auto-upload="true"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">本地上传</el-button>
                </el-upload>
              </div>
              <p style="font-size: 12px" v-if="imgLoopUrl != ''">
                图片路径：{{ imgLoopUrl }}
                <el-button
                  class="tag-read"
                  type="text"
                  :data-clipboard-text="imgLoopUrl"
                  @click="copy"
                  icon="el-icon-edit"
                  size="mini"
                  >复制</el-button
                >
              </p>
              <div :class="{'swiperImg':true,'flex':!loopCode}">
                <el-form-item
                label
                v-for="(item, index) in editForm.info[0].imgs"
                :key="index"
              >
                <el-input
                  v-model="editForm.info[0].imgs[index]"
                  v-if="loopCode"
                ></el-input>
                <img :src="editForm.info[0].imgs[index]" v-if="!loopCode" />
              </el-form-item>
              </div>
              
            </el-tab-pane>
            <div class="rigEnd">
              <el-button
                v-show="activeIndex != 0"
                type="primary"
                class="previousBtn"
                @click="_previousStep"
                >上一步</el-button
              >
              <el-button
                v-show="activeIndex != 3"
                type="primary"
                class="saveBtn"
                @click="_nextStep"
                >下一步</el-button
              >
              <!-- <el-button
                v-show="activeIndex==1"
                type="primary"
                class="saveBtn"
                @click="_saveTemplate"
              >保存</el-button>-->
              <el-button type="success" @click="editSuccess">修改</el-button>
            </div>
          </el-tabs>
        </el-form>
        <!-- <div
          style="width:100%;display: flex;justify-content: center;margin:30px 0"
          v-if="activeIndex==3"
        >
          <el-button type="success" @click="editSuccess">修改</el-button>
        </div> -->
      </el-card>
    </div>
  </div>
</template>

<script>
import editors from "../wangeditor";
import Clipboard from "clipboard";
export default {
  components: { editors },
  data() {
    return {
      canUse0: false,
      canUse1: false,
      activeIndex: 0,
      editFormRules: {
        good_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        inventory: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        colour: {},
      },
      fileList: [],
      fmImgCode: false,
      loopCode: false,
      editForm: {
        info: [{ colour: [], edition: [{ inventory: "" }] }],
      },
      value2: true,
      resquestForm: {
        token: window.sessionStorage.getItem("token"),
        good_name: "",
        type_id: null,
        type_parent_id: 0,
        price: null,
        img: "",
        imgs: [], // 图片的数组
        info: "",
        is_new: null,
        colour: {},
        edition: [
          {
            optional: {},
            generated: { pic: "", price: "" },
            inventory: "",
          },
        ],
        good_id: "",
      },
      imgLoopUrl: "",
      imgDetailUrl: "",
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log('即将离开的标签页名字是：' + oldActiveName)
      //   // console.log('即将进入的标签页名字是：' + activeName)
      //   // console.log(this.canUse0)
      //   if (oldActiveName === '0' && this.canUse0 == false) {
      //     this.$message.error('请先填写完整信息')
      //     return false
      //   }
      //   else if (oldActiveName === '0' && activeName != '1') {
      //     return false
      //   }
      //   if (oldActiveName === '1' && activeName != '0' && this.canUse1 == false) {
      //     this.$message.error('请先填写完整信息')
      //     return false
      //   }
    },
    // 上一步
    _previousStep() {
      this.activeIndex = Number(this.activeIndex);
      this.activeIndex--;
      this.activeIndex = String(this.activeIndex);
    },
    // 下一步步骤
    _nextStep() {
      if (this.activeIndex == 0) {
        if (this.editForm.good_name) {
          if (this.editForm.price) {
            if (this.editForm.type_id) {
              //  if(this.sup){
              var flag = false;
              for (const i in this.editForm.colour) {
                if (this.editForm.colour[i]) {
                  flag = false;
                } else {
                  flag = true;
                }
              }
              if (flag == false) {
                this.canUse0 = true;
                this.activeIndex = Number(this.activeIndex);
                this.activeIndex++;
                this.activeIndex = String(this.activeIndex);
              } else {
                this.$message("请输入商品参数值");
              }
              //  } else{
              //      this.$message('请输入商品参数名称');
              //  }
            } else {
              this.$message("请选择商品类型");
            }
          } else {
            this.$message("请填写商品价格");
          }
        } else {
          this.$message("请填写商品名称");
        }
      } else if (this.activeIndex == 1) {
        // if(this.newTemplateData.length>0){
        // if(this.skuFlag){
        this.canUse1 = true;
        this.activeIndex = Number(this.activeIndex);
        this.activeIndex++;
        this.activeIndex = String(this.activeIndex);
        // }
        // else{
        //     this.$message('请先保存商品规格信息');
        // }
        // }
        // else{
        //     this.$message('请添加商品规格');
        // }
      } else if (this.activeIndex == 2) {
        this.activeIndex = Number(this.activeIndex);
        this.activeIndex++;
        this.activeIndex = String(this.activeIndex);
      }
      // console.log('页面渲染',this.newTemplateData)
    },
    // 3444444444444444444444444444444444
    async getGoodsList() {
      const paramsid = this.$route.query.id;
      // console.log(paramsid)

      const { data: res } = await this.$http.post("/api/admin/goodInfo", {
        token: sessionStorage.getItem("token"),
        good_id: paramsid,
      });
      this.editForm = res.data;
      // console.log('请求获取数据',this.editForm)
      let tmp = JSON.parse(JSON.stringify(this.editForm));
      this.editForm = tmp;
      // console.log(this.editForm);
      let editionArr = JSON.parse(this.editForm.info[0].edition);
      this.editForm.info[0].edition = editionArr;
      let colourObj = JSON.parse(this.editForm.info[0].colour);
      this.editForm.info[0].colour = colourObj;
      let imgsArr = JSON.parse(this.editForm.info[0].imgs);
      this.editForm.info[0].imgs = imgsArr;
      // console.log(this.editForm);
      let value = JSON.parse(this.editForm.is_new);
      if (value == 0) {
        this.value2 = false;
      } else {
        this.value2 = true;
      }
      // console.log(this.editForm)
      this.spuTags = Object.keys(this.editForm.info[0].colour);
      this.skuTags = Object.keys(this.editForm.info[0].edition[0].optional);
      // console.log(this.spuTags)
      // console.log('xaingxi', this.editForm.info[0])
    },
    //修改封面
    setimg() {
      this.fmImgCode = !this.fmImgCode;
    },
    switchChange(val) {
      //console.log(val)
      //this.value2=val

      if (val) {
        this.editForm.is_new = 1;
      } else {
        this.editForm.is_new = 0;
      }
    },
    //修改轮播图
    setLoop() {
      this.loopCode = !this.loopCode;
    },
    uploadFile(file) {
      let formDatas = new FormData();
      formDatas.append("img", file.file);
      this.$http.post("/api/savePic", formDatas).then((res) => {
        // console.log('封面',res)
        this.editForm.img = `http://api_dev.wanxikeji.cn/${res.data.data}`;
      });
    },
    uploadFile2(file) {
      let formDatas = new FormData();
      formDatas.append("img", file.file);
      this.$http.post("/api/savePic", formDatas).then((res) => {
        // console.log('封面',res)
        this.imgLoopUrl = `http://api_dev.wanxikeji.cn/${res.data.data}`;
      });
    },
    uploadFile3(file) {
      let formDatas = new FormData();
      formDatas.append("img", file.file);
      this.$http.post("/api/savePic", formDatas).then((res) => {
        // console.log('封面',res)
        this.imgDetailUrl = `http://api_dev.wanxikeji.cn/${res.data.data}`;
      });
    },
    handleRemove(val) {
      //    console.log(val)
    },
    handlePreview(val) {
      //    console.log(val)
    },
    handleExceed(val) {
      //    console.log(val)
    },
    copy() {
      var clipboard = new Clipboard(".tag-read");
      clipboard.on("success", (e) => {
        this.$message.success("复制成功");
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", (e) => {
        // 不支持复制
        this.$message.error("该浏览器不支持自动复制");
        // 释放内存
        clipboard.destroy();
      });
    },
    async editSuccess() {
      // console.log('修改完成',JSON.parse(this.editForm.info[0].info))

      this.resquestForm.good_name = this.editForm.good_name;
      this.resquestForm.type_id = this.editForm.type_id;
      this.resquestForm.type_parent_id = this.editForm.type_parent_id;
      this.resquestForm.price = this.editForm.price;
      this.resquestForm.img = this.editForm.img;
      this.resquestForm.imgs = this.editForm.info[0].imgs;

      this.resquestForm.is_new = this.editForm.is_new;
      this.resquestForm.colour = this.editForm.info[0].colour;
      this.resquestForm.edition = this.editForm.info[0].edition;
      this.resquestForm.good_id = this.editForm.good_id;
      this.resquestForm.info = window.localStorage.getItem("info");

      const { data: res } = await this.$http.post(
        "/api/admin/addModifyGood",
        this.resquestForm
      );
      if (res.code != 2000) return this.$message.error("修改失败!");
      this.$message.success("修改成功!");
      this.$router.push("/categories");
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  width: 70%;
  margin-left: 15%;
}
/deep/.table-data {
  height: 100%;
}
.upload-demo {
  margin-bottom: 10px;
}
.rigEnd {
  text-align: center;
}
/deep/.el-tag:hover {
  cursor: pointer;
}
/deep/.el-upload-list--text {
  display: none !important;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.el-switch {
  margin-top: 10px;
}
/deep/.input-new-tag {
  width: 90px !important;
  margin-left: 10px;
  vertical-align: bottom;
}

.container {
  min-height: 850px;
  background: #f6f6f6;
  padding-top: 20px;

  .table-data {
    padding: 0 20px;
  }

  .nav-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  /deep/.el-table td,
  /deep/.el-table th {
    text-align: center;
  }
  /deep/.el-form-item__label {
    width: 100px !important;
  }
  /deep/.el-input {
    width: 98%;
  }

  /deep/.el-tabs__nav.is-left {
    // font-size: 20px;
    padding: 0 50px;
  }
  /deep/.el-tabs__item.is-left {
    height: 60px;
    line-height: 60px;
  }
  /deep/.el-tabs__content {
    padding-left: 30px;
    min-height: 200px;
  }
  .flex-row {
    display: flex;
    column-gap: 20px;
  }
  .coverImg .el-form-item__content {
    width: 100%;
  }
  .coverImg img {
    max-width: 30%;
    min-width: 20%;
    display: block;
  }
  .banner-title{
    font-size: 14px;
    background-color: #ccc9;
    padding: 10px 0;
    margin: 0 0 10px 0;
    padding-left: 15px;
  }

  .flex{
    display: flex;
    column-gap: 20px;
    flex-wrap: wrap
  };
  .flex .el-form-item{
    max-width: 20%;
    min-width: 10%;
  }
  .swiperImg .el-form-item img{
    width: 100%;
  }
  

}
</style>